// pages/create/water/water.js
var imageUtil = require('../../../utils/util.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    templateImg:"https://media.hhui.top/ximg/mark/OVERRIDE_RIGHT_BOTTOM.jpg",
    imgPrefix: "https://media.hhui.top/ximg/mark/",
    imagewidth: 0,//缩放后的宽  
    imageheight: 0,//缩放后的高  
    menuList: {},
    img: null,
    logo: null,
    info: "",
    signEnable:true,  // 是否开启签名
    submitDisabled: false,
    range : [],
    styles : [
      {
        name: "右下角",
        style: "OVERRIDE_RIGHT_BOTTOM"
      },
      {
        name: "右居中",
        style: "OVERRIDE_RIGHT_CENTER"
      },
      {
        name: "右上角",
        style: "OVERRIDE_RIGHT_TOP"
      },
      {
        name: "左下角",
        style: "OVERRIDE_LEFT_BOTTOM"
      },
      {
        name: "左居中",
        style: "OVERRIDE_LEFT_CENTER"
      },
      {
        name: "左上角",
        style: "OVERRIDE_LEFT_TOP"
      },
      {
        name: "上居中",
        style: "OVERRIDE_TOP_CENTER"
      },
      {
        name : "正中心",
        style: "OVERRIDE_CENTER"
      },
      {
        name: "下居中",
        style: "OVERRIDE_BOTTOM_CENTER"
      },
      {
        name: "全背景",
        style: "FILL_BG"
      }
      ],
    styleIndex : 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 设置menu
    var menu = getApp().globalData.imgMenuList;
    this.setData({
      menuList: menu
    });
  },
  imageLoad: function (e) {
    var imageSize = imageUtil.imageUtil(e)
    var range = [];
    for (var i = 0; i < this.data.styles.length; i++) {
      range[i] = this.data.styles[i].name;
    }
    console.log("range", range);

    this.setData({
      imagewidth: imageSize.imageWidth,
      imageheight: imageSize.imageHeight,
      leftSize: imageSize.left,
      range: range
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  changeType: function (e) {
    var value = e.currentTarget.dataset.value;
    var index = e.currentTarget.dataset.index;
    console.log(value);

    if (getApp().globalData.imgMenuList.currentMenu == index) {
      return;
    }

    getApp().globalData.imgMenuList.currentMenu = index;
    wx.redirectTo({
        url: value
      })

    // if (value == "/pages/create/template/template") {
      // wx.switchTab({
        // url: value
      // })
    // } else {
      // wx.navigateTo({
        // url: value
      // })
    // }
  },


  // 图片选择
  chooseMainImg: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          img: res.tempFilePaths
        });
      }
    })
  },
  chooseLogo: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          logo: res.tempFilePaths
        });
      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: [e.currentTarget.id] // 需要预览的图片http链接列表
    })
  },
  signChange: function (e) {
    this.setData({
      signEnable: e.detail.value
    });
    console.log(this.data);
  },

  // 选择不同的样式
  bindCountryChange: function(e) {
    var index = e.detail.value;
    var newImg = this.data.imgPrefix + this.data.styles[index].style + ".jpg";
    console.log("new img:", newImg);
    this.setData({
      styleIndex : index,
      templateImg : newImg
    })
  },

  // 提交数据
  bindFormSubmit: function(e) {
    if (this.data.img == null) {
      wx.showToast({
        title: '请选择一张图片',
        icon: 'success',
        duration: 1500
      });
      return;
    }

    if (this.data.submitDisabled) {
      return;
    }

    // 设置btn为不可点击
    this.setData({ submitDisabled: true });
    wx.showToast({
      title: '努力生成中...',
      icon: 'loading'
    });

    var path = getApp().globalData.host;
    var that = this;


    // 设置提交的参数
    var signEnable = this.data.signEnable ? 1 : 0;
    var sign = e.detail.value.signarea;
    var logo = this.data.logo;
    var tempFile = this.data.img[0];
    var logoUrl = "";
    var logoHeight = e.detail.value.logoHeight;
    var rotate = e.detail.value.rotate;
    var opacity = e.detail.value.opacity;
    var style = this.data.styles[this.data.styleIndex].style;

    if(logo != null && logo.length == 1) {
      wx.uploadFile({
        url: path + "wx/wx/upload",
        header: {
          'Content-Type': 'application/json'
        },
        filePath: logo[0],
        name: 'image',
        success: function(res) {
          var ans = JSON.parse(res.data);
          logoUrl = ans.result.img;
          

          wx.uploadFile({
            url: path + 'wx/wx/water',
            // url: 'http://127.0.0.1:8080/wx/water', //仅为示例，非真实的接口地址
            header: {
              'Content-Type': 'application/json'
            },
            filePath: tempFile,
            name: 'image',
            formData: {
              "style": style,
              "sign": sign,
              "signEnabled": signEnable,
              "logo": logoUrl,
              "rotate": rotate,
              "logoHeight": logoHeight,
              "opacity": opacity
            },
            success: function (res) {
              wx.hideToast();
              that.setData({ submitDisabled: false });

              var data = res.data;

              var ans = JSON.parse(data);
              console.log(ans);
              if (ans['status']['code'] == 200) {
                var imgUrl = path + ans.result.img;
                console.log("img", imgUrl);
                wx.previewImage({
                  current: imgUrl, // 当前显示图片的http链接
                  urls: [imgUrl] // 需要预览的图片http链接列表
                });
              } else {
                wx.showToast({
                  title: '生成失败',
                  icon: 'loading',
                  duration: 1500
                });
              }
            },
            fail: function () {
              wx.showToast({
                title: '生成失败!',
                duration: 1500
              });
              that.setData({ submitDisabled: false });
            }
          })

        },
        fail: function(res) {
          wx.showToast({
            title: 'logo上传失败!',
            duration: 1500
          });
          that.setData({ submitDisabled: false });
        }
      })
    }
  },
})